package com.slm.krstartimes.service;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageLoader;
import com.android.volley.toolbox.Volley;
import com.slm.krstartimes.R;
import com.slm.krstartimes.activity.NewsDetailActivity;
import com.slm.krstartimes.utils.MyImageLoader;
import com.slm.krstartimes.utils.News;
import com.slm.krstartimes.utils.NewsListSAX;
import com.slm.krstartimes.utils.StreamRequest;

import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Timer;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * Created by dllo on 15/8/10.
 */
public class NotificationService extends Service {
    static final int UPDATE_INTERVAL = 1000;
    private static final String TAG = "LocalService";
    MediaPlayer mediaPlayer = null;
    int counter = 0;
    private IBinder binder = new NotificationService.LocalBinder();
    private Handler handler;
    private RequestQueue requestQueue;
    private ImageLoader imageLoader;
    private NotificationManager notificationManager;
    private int notificationID = 0;
    private Timer timer = new Timer();

    @Override
    public IBinder onBind(Intent intent) {

        return binder;
    }

    @Override
    public void onCreate() {
        Log.i(TAG, "onCreate");
        requestQueue = Volley.newRequestQueue(this);
        imageLoader = new ImageLoader(requestQueue, new MyImageLoader());
        //这里可以启动媒体播放器
        // if(mediaPlayer==null)
        //     mediaPlayer=MediaPlayer.create(this, uri);
        super.onCreate();
    }

    public void CreateInform() {
        notificationManager = (NotificationManager) this.getSystemService(android.content.Context.NOTIFICATION_SERVICE);
        StreamRequest request = new StreamRequest("http://api.ithome.com/xml/newslist/news.xml",
                new Response.Listener<InputStream>() {
                    @Override
                    public void onResponse(InputStream inputStream) {
                        handler = new Handler(new Handler.Callback() {
                            @Override
                            public boolean handleMessage(Message message) {
                                if (message.what == 10) {
                                    final List<News> list = (List<News>) message.obj;
                                    for (int i = 1; i < 2; i++) {
                                        //定义一个PendingIntent，当用户点击通知时，跳转到某个Activity(也可以发送广播等)
                                        Intent newsDetail = new Intent(NotificationService.this, NewsDetailActivity.class);
                                        newsDetail.putExtra("newsId", list.get(i).getNewsid());
                                        newsDetail.putExtra("title", list.get(i).getTitle());
                                        newsDetail.putExtra("postdate", list.get(i).getPostdate());
                                        newsDetail.putExtra("hitCount", list.get(i).getHitcount());
                                        PendingIntent pendingIntent = PendingIntent.getActivity(NotificationService.this, 0, newsDetail, 0);
                                        //创建一个通知
                                        Notification notification = new Notification(R.mipmap.appic, list.get(i).getTitle(), System.currentTimeMillis());
                                        notification.setLatestEventInfo(NotificationService.this, list.get(i).getTitle(), "点击查看详细内容", pendingIntent);
                                        notification.flags = Notification.FLAG_AUTO_CANCEL;
                                        //用NotificationManager的notify方法通知用户生成标题栏消息通知
                                        notificationManager.notify(notificationID, notification);
                                        notificationID++;
                                    }
                                }
                                return false;
                            }
                        });

                        SAXParserFactory spx = SAXParserFactory.newInstance();
                        try {
                            SAXParser sp = spx.newSAXParser();
                            sp.parse(inputStream, new NewsListSAX(handler));

                        } catch (ParserConfigurationException e) {
                            e.printStackTrace();
                        } catch (SAXException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {

            }
        });
        requestQueue.add(request);

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "onStartCommand");
        while (true) {
            final Handler handler = new Handler();
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    // TODO Auto-generated method stub
                    //要做的事情
                    CreateInform();
                    handler.postDelayed(this, 1000 * 60 * 10);
                }
            };
            handler.postDelayed(runnable, 1000 * 60 * 10);//每--执行一次runnable.
            return START_STICKY;
        }
    }


    @Override
    public void onDestroy() {
        Log.i(TAG, "onDestroy");
        super.onDestroy();
    }


    //定义内容类继承Binder
    public class LocalBinder extends Binder {
        //返回本地服务
        NotificationService getService() {
            return NotificationService.this;
        }
    }
}

